﻿using Newtonsoft.Json;
using StackExchange.Redis;
using WebAPItest.Models.Database;
using System;
using System.Security.Cryptography;
using System.Collections.Generic;
using WebAPItest.Models;

namespace WebAPItest.Service
{
    public class RedisService:IRedisService
    {
        private readonly IDatabase _redis;
        private readonly IRedisService _redisService;
        private readonly WebEnterpriseIIContext _db;
        public RedisService(RedisHelper client, IRedisService redisService, WebEnterpriseIIContext db)
        {
            _redis = client.GetDatabase();
            _redisService = redisService;
            _db = db;
        }
        /// <summary>
        /// 添加商品浏览记录
        /// </summary>
        /// <returns></returns>
        public void AddGoodViews(int userId,Good good)
        {
            //之前缓存下来的浏览记录  每个用户浏览记录都是单独的 每个用户都有自己的key  UserViews28\UserViews20
            // 
            var key = $"UserViews{userId}";

            //在用户浏览商品的时候  添加商品浏览记录  商品
            //新数据在左边还是右边
            //新  旧


            var jsonStr = JsonConvert.SerializeObject(good);//序列化
            _redis.ListLeftPush(key, jsonStr);
        }

        /// <summary>
        /// 查询商品浏览记录
        /// </summary>
        /// <returns></returns>
        public List<Good> GetUserViews(int userId)
        {
            var key = $"UserViews{userId}";
            var data = _redis.ListRange(key, 0, 4);
            var list = new List<Good>();
            foreach (var item in data)
            {
                var good = JsonConvert.DeserializeObject<Good>(item);
                list.Add(good);
            }
            return list;
        }
    }
}
